"""
---------------------------------------------------------------------
- File: config.py
- Date: 2025/11/5
- Author: yangzhide
- Email: xxzjyzd@126.com
- Description: 配置文件（使用Pydantic BaseSettings）
---------------------------------------------------------------------
"""

import os
from pathlib import Path
from typing import Literal

from dotenv import load_dotenv
from pydantic_settings import BaseSettings, SettingsConfigDict

from app.core.logs import logger

# from app.core.log import app_logger

# 1. 加载.env文件并设置环境变量，为后续添加配置项做准备
BASE_DIR = Path(__file__).resolve().parent.parent.parent
load_dotenv(dotenv_path=BASE_DIR / ".env")
# 2. 获取环境变量
APP_ENV = os.getenv("APP_ENV", "development")


class Settings(BaseSettings):
    """
    项目配置类, 自动读取配置文件
    pydantic-settings 会首先尝试加载 .env 文件（如果存在），
    """

    # ---项目环境---
    # 项目名称
    PROJECT_NAME: str = "后端FastAPI接口"
    # 数据库配置
    ASYNC_DATABASE_URL: str = ""
    # 当前环境
    APP_ENV: Literal["development", "testing", "production"] = "development"
    # 调试模式
    DEBUG: bool = False

    # ---jwt配置---
    # 密钥配置
    ALGORITHM: str
    # 加密码
    SECRET_KEY: str
    # 令牌有效期（分钟）
    ACCESS_TOKEN_EXPIRE_MINUTES: int

    @staticmethod
    def get_env_file():
        valid_envs = ["development", "testing", "production"]
        if APP_ENV in valid_envs:
            return f".env.{APP_ENV}"
        logger.error(f"无效的环境变量 APP_ENV: {APP_ENV}, valid values: {valid_envs}")
        raise ValueError(f"无效的环境变量 APP_ENV: {APP_ENV}, valid values: {valid_envs}")

    model_config = SettingsConfigDict(
        env_file=(get_env_file()),
        env_file_encoding="utf-8",
        extra="ignore",  # 忽略多余的配置项
    )


settings = Settings()

logger.info(f"当前环境: {settings.APP_ENV}")
logger.info(f"数据库配置: {settings.ASYNC_DATABASE_URL}")
